package com.xinpan.exercise;

public class StringToInteger {
    public int atoi(String str) {
        // Start typing your Java solution below
        // DO NOT write main() function
        if(str.length() == 0)   
            return 0;
        int i = 0;
        while(str.charAt(i) == ' ') i++;
        
        boolean pos = true;
        if(str.charAt(i) == '-')
        {
            pos = false;
            i++;
        }
        else if(str.charAt(i) == '+')
            i++;
        
        long res = 0;
        for(; i < str.length(); i++)
        {
            int v = str.charAt(i) - '0';
            if(v < 0 || v > 9)
                break;

            res = res * 10 + v;
            if(res > (long)Integer.MAX_VALUE)
            {
                if(pos)
                    return Integer.MAX_VALUE;
                else
                    return Integer.MIN_VALUE;
            }
        }
        if(!pos)
            return 0 - (int)res;
        else
            return (int)res;
    }
}
